<template>
  <div class="Advertising" v-loading.lock="fullscreenLoading">
    <div class="Advertising__top"><nuxt-link style="color: #409eff;padding:8px;" to='/advertising/menager'>返回</nuxt-link></div>
    <el-card class="Advertising__card">
      <el-form :model="addForm" ref="addForm" label-width="100px" label-position="left" class="Advertising__form">
        <el-form-item
          prop="title"
          :rules="[
            { required: true, message: '广告标题不能为空'}
          ]"
         label="广告标题">
         <el-input v-model="addForm.title" style="width:194px;" size="mini" placeholder="单行输入"></el-input>
        </el-form-item>
        <el-form-item
          label="链接"
          prop="bindingId"
          :rules="[
            { required: addForm.type!='', message: '请选择店铺或商品'}
          ]"
        >
          <el-dropdown @command="changeType" trigger="click">
            <el-input        
              style="width:194px;cursor:pointer;"
              clearable
              placeholder="选择店铺或商品"
              suffix-icon="el-icon-arrow-down"
              readonly
              @clear="clearBindingRow"
              :value="addForm.bindingName">
            </el-input>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item key="NULL" command="NULL">无</el-dropdown-item>
              <el-dropdown-item
                v-for="item in typeList" :key="item.code"
                :command="item.code">{{item.text}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <span class="Advertising__form__bindName">{{'店铺(商品)名称'}}</span> -->
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="startTime"
          :rules="[
            { required: true, message: '请设置开始时间'}
          ]"
        >
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="addForm.startTime" style="width:194px;" size="mini" type="datetime" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="结束时间"
          prop="endTime"
          :rules="[
            { required: true, message: '请设置结束时间'}
          ]"
        >
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="addForm.endTime" style="width:194px;" size="mini" type="datetime" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="投放地区"
          prop="areas"
          :rules="[
            { required: true, message: '请设置投放地区'}
          ]"
        >
          <no-ssr>
            <el-cascader @change="changeAreas" v-model="addForm.areas" style="width:194px;" change-on-select size="mini" clearable :options="regionData"  placeholder="省/市/区"></el-cascader>
          </no-ssr>
        </el-form-item>
      </el-form>
      <el-form label-width="100px" label-position="left" class="Advertising__form__right">
        <el-form-item
          prop="imageUrl"
          :rules="[
            { required: true, message: '轮播图片不能为空'}
          ]"
         label="轮播图片">
         <ecp-upload title="点击上传广告图片" v-model="addForm.imageUrl"/>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="Advertising__chart" v-if="this.$route.params.id!=0">
      <div class="Advertising__chart__header">
        <div class="Advertising__chart__header__left">
          <el-date-picker v-model="adChart.startTime" value-format="yyyy-MM-dd" style="width:128px;margin-right: 32px;" type="date" placeholder="起始日期"></el-date-picker>
          <el-date-picker v-model="adChart.endTime" value-format="yyyy-MM-dd" style="width:128px;margin-right:10px;" type="date" placeholder="结束日期"></el-date-picker>
          <el-button size="mini" type="primary" @click.native="getCountNumberList" icon="el-icon-refresh" circle></el-button>
        </div>
      </div>
      <p style="text-align:center;padding:30px 0;" v-show="adChart.noData">暂无数据</p>
      <div v-show="!adChart.noData" style="width: 936px;height:384px;" ref="adChart"></div>
    </el-card>
    <div class="Advertising__bottom">
      <el-button type="primary" round  @click.native="addAdvertising" v-if="!$route.params.id==0">发布</el-button>
    </div>
    <!-- 店铺列表弹窗 -->
    <el-dialog
      class="Advertising__dialog"
      :visible.sync="dialogs.SHOP"
      top="50px"
      width="480px">            
      <div slot="title">
        <el-input v-model="dialogs.searchText" style="width:194px;margin-right:10px;" size="mini" placeholder="搜索店铺"></el-input>
        <el-button size="mini" type="primary" @click="getSupplyShopList(1)">搜 索</el-button>
      </div>
      <el-table
        :data="dialogs.supplyShopList" height="400px">
        <el-table-column label="店铺名称">
          <template slot-scope="scope">
            <el-radio v-model="dialogs.bindingRow" :label="scope.row">{{scope.row.name}}</el-radio>
          </template>
        </el-table-column>
        <!-- <el-table-column width="160" property="name" label="店铺名称"></el-table-column> -->
        <el-table-column label="店铺地址">
          <template slot-scope="scope">
            <span>{{`${scope.row.provinceName}${scope.row.cityName}${scope.row.districtName}${scope.row.address}`}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        small
        v-show="dialogs.total>0"
        @current-change="getSupplyShopList"
        :current-page="dialogs.pageNum"
        layout="prev, pager, next"
        :total="dialogs.total">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogs.SHOP = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleDialogsClose('SHOP')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 商品列表弹窗 -->
    <el-dialog
      class="Advertising__dialog"
      :visible.sync="dialogs.GOODS"
      top="50px"
      width="480px">
      <div slot="title">
        <el-input v-model="dialogs.searchText" style="width:194px;margin-right:10px;" size="mini" placeholder="搜索商品"></el-input>
        <el-button size="mini" type="primary" @click="getGoodsList(1)">搜 索</el-button>
      </div>
      <el-table
        :data="dialogs.goodsList" height="400px">
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            <el-radio v-model="dialogs.bindingRow" :label="scope.row">{{scope.row.goodsName}}</el-radio>
          </template>
        </el-table-column>
        <!-- <el-table-column property="goodsName" label="商品名称"></el-table-column> -->
        <el-table-column property="name" label="店铺名称"></el-table-column>
        <el-table-column label="店铺地址">
          <template slot-scope="scope">
            <span>{{`${scope.row.provinceName}${scope.row.cityName}${scope.row.districtName}${scope.row.address}`}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        small
        v-show="dialogs.total>0"
        @current-change="getGoodsList"
        :current-page="dialogs.pageNum"
        layout="prev, pager, next"
        :total="dialogs.total">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogs.GOODS = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="handleDialogsClose('GOODS')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
if (process.browser) {
  var {regionData, CodeToText} = require('element-china-area-data')
}
import EcpUpload from '~/components/ecpUpload'
import echarts from 'echarts'
import { getEcpAdvertisement, getCountNumberList, getGoodsList, getSupplyShopList, addEcpAdvertisement,getAdvertisementTypeList,updateEcpAdvertisement} from "~/api/";
  export default {
    components: {
      EcpUpload
    },
    data() {
      return {
        regionData,
        fullscreenLoading: true,
        dialogs: {
          GOODS: false,
          SHOP: false,
          searchText: '',
          goodsList:[],
          supplyShopList:[],
          pageNum: 1,
          pageSize: 15,
          total: 0,
          totalNum: 1,
          bindingId: '',
          bindingRow: {
            id: '',
            goodsName: '',
            name:''
          }
        },
        adChart: {
          startTime: '',
          endTime: '',
          noData: true
        },
        addForm:{
          title: '',
          startTime: '',
          endTime: '',
          type: '',
          bindingId: '',
          bindingName: '',
          imageUrl: '',
          provinceCode: 0,
          provinceName: '',
          cityCode: 0,
          cityName: '',
          districtCode: 0,
          districtName: '',
          areas:[]
        }
      }
    },
    async asyncData({ app, params }) {
      try {
        const res = await getAdvertisementTypeList(app);
        if (res.code == "0") return { typeList: res.data.typeList };
        return { typeList: [], message: res.message };
      } catch (error) {
        console.error(`获取广告类型列表接口错误，错误信息${error}`);
      }
    },
    mounted() {
      if (this.$route.params.id == 0) {
        this.fullscreenLoading = false
      } else {
        this.getEcpAdvertisement()
      }
    },
    methods: {
      changeAreas (areas) {
        console.log(areas)
        this.addForm.provinceCode = areas[0]||0
        this.addForm.provinceName = CodeToText[areas[0]]
        this.addForm.cityCode = areas[1]
        this.addForm.cityName = CodeToText[areas[1]]
        this.addForm.districtCode = areas[2]
        this.addForm.districtName = CodeToText[areas[2]]
      },
      clearBindingRow () {
        // 清空商品或店铺链接
        this.addForm.bindingId = ''
        this.addForm.bindingName = ''
        this.addForm.type = ''

        this.dialogs.bindingRow.id = ''
        this.dialogs.bindingRow.goodsName = ''
        this.dialogs.bindingRow.name = ''
      },
      handleDialogsClose (type) {
        this.addForm.bindingId = this.dialogs.bindingRow.id
        if (type == 'GOODS') {
          this.addForm.bindingName = this.dialogs.bindingRow.goodsName
        } else if (type == 'SHOP') {
          this.addForm.bindingName = this.dialogs.bindingRow.name
        }
        this.dialogs[type] = false
      },
      changeType (type) {
        // this.dialogs.bindingId = ''
        if (type == 'NULL') {
          this.clearBindingRow()
          return
        }else if (type == 'GOODS') {
          this.getGoodsList()
        } else if (type == 'SHOP') {
          this.getSupplyShopList()
        }
        this.addForm.type = type
        this.dialogs[type] = true
      },
      async getGoodsList (pageNum=1) {
        const res = await getGoodsList(this, this.dialogs.searchText, pageNum,15)
        if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
        this.dialogs.goodsList = res.data.page.list
        this.dialogs.pageNum = res.data.page.pageNum
        this.dialogs.pageSize = res.data.page.pageSize
        this.dialogs.total = res.data.page.total
        this.dialogs.totalNum = res.data.page.totalNum

      },
      async getSupplyShopList (pageNum=1) {
        const res = await getSupplyShopList(this, this.dialogs.searchText, pageNum,15)
        if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
        this.dialogs.supplyShopList = res.data.page.list
        this.dialogs.pageNum = res.data.page.pageNum
        this.dialogs.pageSize = res.data.page.pageSize
        this.dialogs.total = res.data.page.total
        this.dialogs.totalNum = res.data.page.totalNum
      },
      async getEcpAdvertisement () {
        // 获取广告
        const res = await getEcpAdvertisement(this, this.$route.params.id)
        if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
        const {title,startTime,endTime,type,bindingId,imageUrl,provinceCode,provinceName,cityCode,cityName,districtCode,districtName} = res.data.ecpAdvertisementInfo
        this.addForm.title = title
        this.addForm.startTime = startTime
        this.addForm.endTime = endTime
        this.addForm.type = type
        this.addForm.bindingId = bindingId
        this.addForm.bindingName = res.data.ecpAdvertisementInfo.bindingName||''
        this.addForm.imageUrl = imageUrl
        this.addForm.provinceCode = provinceCode
        this.addForm.provinceName = provinceName
        this.addForm.cityCode = cityCode
        this.addForm.cityName = cityName
        this.addForm.districtCode = districtCode
        this.addForm.districtName = districtName
        this.addForm.areas = [provinceCode,cityCode,districtCode]

        this.adChart.startTime = startTime
        this.adChart.endTime = endTime
        this.getCountNumberList()
      },
      async getCountNumberList () {
        // 获取广告浏览量统计
        const res = await getCountNumberList(this, this.$route.params.id, this.adChart.startTime, this.adChart.endTime)
        if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
        let categorys = []
        let datas = []
        res.data.countNumberList.map(item =>{
          categorys.push(item.dateTime)
          datas.push(item.countNumber)
        })
        this.fullscreenLoading = false
        this.creatEcart(categorys, datas)
      },
      creatEcart(categorys, datas) {
        const el = this.$refs.adChart
        const myChart = echarts.init(el)
        // 指定图表的配置项和数据
        var option = {
          xAxis: {
              type: 'category',
              data: categorys
          },
          yAxis: {
              type: 'value'
          },
          series: [{
              data: datas,
              type: 'line'
          }],
          color: ['#409eff', '#ff0000']
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    },
    addAdvertising() {
      this.$refs["addForm"].validate(async valid => {
        if (!valid) return
        let res
        const {title,startTime,endTime,type,bindingId,imageUrl,provinceCode,provinceName,cityCode,cityName,districtCode,districtName} = this.addForm
        if (this.$route.params.id == 0) {
          // 新增广告
          res = await addEcpAdvertisement( this, {
            title,startTime,endTime,type,
            bindingId,imageUrl,provinceCode,provinceName,
            cityCode,cityName,districtCode,districtName
          })
        } else {
          // 修改广告
          res = await updateEcpAdvertisement(this, {
            id: this.$route.params.id,
            title,startTime,endTime,type,
            bindingId,imageUrl,provinceCode,provinceName,
            cityCode,cityName,districtCode,districtName
          })
        }
        if (res.code != '0') return this.$alert(res.message, '提示', {type: 'error'})
        //成功处理
        this.$message.success(this.$route.params.id == 0 ? "添加成功" : '修改成功')
        this.$router.replace("/advertising/menager")
      })
    }
    },
  }
</script>

<style lang="scss" scoped>
.Advertising {
  padding: 0px 50px;
  background-color: #f5f9fe;
  &__dialog {
    & /deep/ {
      .el-pagination {
        text-align: center;
      }
      .el-dialog__body {
        padding: 0 10px;
      }
      .el-dialog__footer {
        padding: 0 20px 10px;
      }
      // .el-table--enable-row-hover .el-table__body tr:hover>td {
      //   background-color: #84dba7;
      // }
      // .el-table__body tr.current-row > td {
      //   background-color: #84dba7;
      // }
    }
  }
  &__chart {
    margin-top: 15px;
    &__header {
      line-height: 25px;
      padding-bottom: 15px;
      &__right {
        float: right;
      }
      & /deep/ {
        .el-button--primary {
          border-radius: 9px;
          width: 70px;
          padding: 5px 20px;
        }
        .el-input__icon {
          height: 25px;
          line-height: 25px;
        }
        .el-input__inner{
          height: 25px;
          line-height: 25px;
          background-color: #f0f5fb;
	        border-radius: 9px;
          border: none;
        }
        .el-radio-group {
          .is-bordered {
            padding: 0 6px;
            height: 25px;
            line-height: 25px;
            border: none;
            .el-radio__label {
              font-size: 16px;
              color: #409EFF;
            }
          }
        }
      }
    }
  }
  &__form {
    display: inline-block;
    width: 550px;
    &__bindName {
      font-size: 16px;
      display: inline-block;
      margin-left: 16px;
      max-width: 240px;
      color: #409eff;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      word-break: break-all;
      vertical-align: middle;
    }
    & /deep/ {
      .el-input__icon {
        line-height: 30px;
      }
      .el-input__inner, .el-input--suffix{
        height: 30px;
        line-height: 30px;
        border-radius: 15px;
      }
      .el-form-item__label {
        line-height: 30px;
        font-size: 16px;
        color: #409eff;
      }
      .el-form-item__content {
        line-height: 30px;
        input {
          font-size: 14spx;
        }
      }
    }
    &__right {
      float: right;
      margin-top: 110px;
      margin-right: 20px;
      & /deep/ {
        .el-form-item__label {
          line-height: 30px;
          font-size: 16px;
          color: #409eff;
        }
        .Upload {
          margin-top: -40px;
          .el-upload--picture-card {
            width: 212px;
            height: 100px;
            line-height: 100px;
          }
        }
      }
    }
  }
  &__card {
    & /deep/ {
      .el-card__body {
        padding-left: 40px;
        position: relative;
        &::before{
          content: "";
          display: block;
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background-color: #84dba7;
          position: absolute;
          top: 32px;
          left: 26px;
        }
      }
    }
  }
  &__top {
    line-height:50px;
    text-align:right;
  }
  &__bottom {
    margin-top: 24px;
    line-height:50px;
    text-align:right;
    .el-button--primary {
      font-size: 18px;
      padding: 12px 40px;
      border-radius: 22px;
    }
  }
}
</style>
